package view.backend.backup;

import control.BackupControl;
import exceptionManager.ExceptionManager;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import view.generaldesign.DesignLayout;

/**
 * Denne klasse repræsentere viewet af vores backup.
 *
 * @author Mathias
 */
public class AdminBackup {

    private JPanel backupPanel;
    private JButton btnBackup;
    private JList listBackup;
    private JScrollPane scrollPane;
    private File backuplist;
    private BackupControl startBackup;

    public AdminBackup() {
        //Opretter panelet som bruges til vores backup.
        backupPanel = new JPanel(null);
        backupPanel.setBounds(395, 320, 650, 500);
        backupPanel.setOpaque(false);
        backupPanel.setBorder(BorderFactory.createTitledBorder(DesignLayout.T_FIELD_RED, "", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, DesignLayout.STANDARD));

        //Opretter filen "Backup.txt", hvis filen ikke findes.
        String backupFolder = "backup";
        try {
            backupFolder = folderManager.FolderManager.checkAndCreateFolder(backupFolder);
            String backupFile = backupFolder + "\\backup.txt";
            backuplist = new File(backupFile);
        } catch (Exception e) {
            ExceptionManager.handleException(e);
        }

        //Opretter vores JList.
        listBackup = new JList(getBackupInfo());
        listBackup.setBackground(DesignLayout.T_FIELD_BG_COLOR);
        listBackup.setBackground(Color.WHITE);
        listBackup.setBorder(null);

        //Opretter vores knap, som laver backuppen, samt opdatere vores JList.
        btnBackup = new JButton("Lav Backup");
        btnBackup.setBounds(10, 10, 100, 35);
        btnBackup.setBorder(DesignLayout.T_FIELD_RED);
        btnBackup.setBackground(DesignLayout.T_FIELD_BG_COLOR);
        btnBackup.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //Opretter et pop-up bekræftelsesvindue,
                //hvor man bekræfter at man vil have lavet sin backup.
                int confirm = JOptionPane.YES_NO_OPTION;
                int confirmresult = JOptionPane.showConfirmDialog(null, "Er du sikker på at du vil lave backup af dit system?", "Backup", confirm);
                if (confirmresult == JOptionPane.YES_OPTION) {
                    String dateTime = getDateTime();
                    try {
                        //Indsætter nuværende dato og tid til vores "backup.txt".
                        BufferedWriter output;
                        output = new BufferedWriter(new FileWriter(backuplist, true));
                        output.append(dateTime);
                        output.newLine();
                        output.close();
                    } catch (IOException ex) {
                        ExceptionManager.handleIOException(ex);
                    }
                    try {
                        //Starter vores backup.
                        startBackup.startBackUp(dateTime);
                        //Exceptionhandling for metoden "startBackUp".
                    } catch (ClassNotFoundException ex) {
                        ExceptionManager.handleClassNotFoundException(ex);
                    } catch (SQLException ex) {
                        ExceptionManager.handleSQLException(ex);
                    } catch (IOException ex) {
                        ExceptionManager.handleIOException(ex);
                    }
                }
                updateJList();
            }
        });

        //Opretter et JScrollPane, hvor vores JList bliver indsat,
        //så det bliver muligt at scrolle i vores liste.
        scrollPane = new JScrollPane(null);
        scrollPane.setBounds(350, 10, 290, 480);
        scrollPane.setBorder(null);
        scrollPane.setViewportView(listBackup);
        scrollPane.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, DesignLayout.T_FIELD_BORDER_RED));
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.getVerticalScrollBar().setUnitIncrement(15);

        //Adder vores knap samt vores JScrollPane til vores backup,
        //og panelet bliver derefter sat til at være usynligt indtil det skal bruges.
        backupPanel.add(btnBackup);
        backupPanel.add(scrollPane);
        backupPanel.setVisible(false);
    }

    public JPanel getPanel() {
        return backupPanel;
    }

    /**
     * Denne metode genere dato og tid for det tidspunkt metoden bliver kørt.
     */
    private String getDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("ddMMyyHHmm");
        Date date = new Date();
        return dateFormat.format(date);
    }

    /**
     * Denne metode laver en Arraylist, hvor der indsættes informationen fra
     * vores backup-fil. Arraylisten laves derefter om til et Array, for at det
     * kan indsættes i vores JList.
     */
    private String[] getBackupInfo() {
        ArrayList<String> lines = new ArrayList<>();

        BufferedReader input;
        try {
            input = new BufferedReader(new FileReader(backuplist));
            Scanner scan = new Scanner(input);
            while (scan.hasNext()) {
                lines.add(scan.nextLine());
            }
        } catch (FileNotFoundException ex) {
            BufferedWriter output;
            try {
                output = new BufferedWriter(new FileWriter(backuplist, true));
                output.close();
            } catch (IOException ex1) {
                ExceptionManager.handleIOException(ex1);
            }
        }

        String[] streng = new String[lines.size()];
        for (int i = 0; i < lines.size(); i++) {
            streng[i] = lines.get(i);
        }

        return streng;
    }

    /**
     * Denne metode opdatere vores JList.
     */
    private void updateJList() {
        listBackup.setListData(new Object[]{});
        listBackup.setListData(getBackupInfo());
    }
}
